package com.wuyu.easyid.server.service.id;

import com.wuyu.easyid.base.entity.SegmentId;
import com.wuyu.easyid.base.service.SegmentIdService;
import com.wuyu.easyid.server.dao.IdInfoMapper;
import com.wuyu.easyid.server.model.IdInfo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * ID块服务实现.
 */
@Service
public class SegmentIdServiceImpl implements SegmentIdService {

    /**
     * ID服务信息.
     */
    @Resource
    private IdInfoMapper idInfoMapper;

    @Override
    @Transactional
    public SegmentId getNextSegmentId(Integer bizType) {
        // 有可能存在version冲突，需要重试
        for (int i = 0; i < 3; i++) {
            IdInfo idInfo = idInfoMapper.selectByType(bizType);
            Long newMaxId = idInfo.getMaxId() + idInfo.getStep();
            Long version = idInfo.getVersion();
            int row = idInfoMapper.updateMaxId(idInfo.getId(), version, newMaxId);
            if (row == 1) {
                return new SegmentId(newMaxId, idInfo.getStep());
            }
        }
        throw new RuntimeException("get next segmentId conflict");
    }
}
